package app.itgungnir.compose.wan.business.user_square

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import app.itgungnir.compose.wan.business.main.square.Square
import app.itgungnir.compose.wan.utils.*
import com.google.gson.JsonElement
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow

@Suppress("UNCHECKED_CAST")
class UserSquareViewModelFactory(private val userId: Long) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return when (modelClass.isAssignableFrom(UserSquareViewModel::class.java)) {
            true -> UserSquareViewModel(userId) as T
            else -> throw IllegalArgumentException("Unknown ViewModel class.")
        }
    }
}

class UserSquareViewModel(private val userId: Long) : ViewModel() {

    val loadingState = MutableStateFlow(false)
    val errorState = MutableSharedFlow<Throwable?>()
    var loadingJob: Job? = null

    val dismissDialogState = MutableSharedFlow<Boolean>()

    val userSquareListFlow = when (LocalDataStore.localData.userInfo.id == userId) {
        true -> pagingSourceWithCache(
            firstPageIndex = 1,
            pageSize = 20,
            networkRequest = { pageNo ->
                wanAndroidService.getMySquareList(pageNo).wanResponse<UserSquareResponse>()?.shareArticles
            },
            queryCache = { dao -> dao.querySquares() },
            clearCache = { dao -> dao.deleteAllSquares() },
            appendCache = { list, dao -> dao.insertAllSquares(list) }
        )
        else -> pagingSourceWithoutCache(firstPageIndex = 1, pageSize = 20) { pageNo ->
            wanAndroidService.getUserSquareList(userId, pageNo).wanResponse<UserSquareResponse>()?.shareArticles
        }
    }

    fun addSquare(title: String, link: String) = launch(loadingState = loadingState, errorState = errorState) {
        dismissDialogState.emit(false)
        wanAndroidService.addMySquareArticle(title, link).wanResponse<JsonElement>()
        dismissDialogState.emit(true)
    }

    fun deleteSquare(square: Square?) = launch(loadingState = loadingState, errorState = errorState) {
        square?.let {
            wanAndroidService.deleteMySquareArticle(it.id)
            WanDatabase.dao.deleteSquare(it.id)
        }
    }.also { loadingJob = it }
}
